/*
 * Copyright (C) 2003, 2004, 2005 Joe Walnes.
 * Copyright (C) 2006, 2007 XStream Committers.
 * All rights reserved.
 *
 * The software in this package is published under the terms of the BSD
 * style license a copy of which has been included with this distribution in
 * the LICENSE.txt file.
 * 
 * Created on 01. October 2003 by Joe Walnes
 */
package com.tcoiss.webservice.apiServer.xstream.converters.collections;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Vector;

import com.tcoiss.webservice.apiServer.xstream.converters.MarshallingContext;
import com.tcoiss.webservice.apiServer.xstream.converters.UnmarshallingContext;
import com.tcoiss.webservice.apiServer.xstream.core.JVM;
import com.tcoiss.webservice.apiServer.xstream.io.HierarchicalStreamReader;
import com.tcoiss.webservice.apiServer.xstream.io.HierarchicalStreamWriter;

/**
 * Converts most common Collections (Lists and Sets) to XML, specifying a nested
 * element for each item.
 * <p/>
 * <p>Supports java.utils.ArrayList, java.utils.HashSet,
 * java.utils.LinkedList, java.utils.Vector and java.utils.LinkedHashSet.</p>
 *
 * @author Joe Walnes
 */
public class CollectionConverter extends AbstractCollectionConverter {

	public boolean canConvert(Class type) {
		return type.equals(ArrayList.class) || type.equals(HashSet.class) ||
			type.equals(LinkedList.class) || type.equals(Vector.class) ||
			(JVM.is14() && type.getName().equals("java.utils.LinkedHashSet"));
	}

	public void marshal(Object source, HierarchicalStreamWriter writer,
		MarshallingContext context) {
		Collection collection = (Collection) source;
		for (Iterator iterator = collection.iterator(); iterator.hasNext();) {
			Object item = iterator.next();
			writeItem(item, context, writer);
		}
	}

	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
		Collection collection = (Collection) createCollection(context.getRequiredType(),
			context);
		populateCollection(reader, context, collection);
		return collection;
	}

	protected void populateCollection(HierarchicalStreamReader reader,
		UnmarshallingContext context, Collection collection) {
		while (reader.hasMoreChildren()) {
			reader.moveDown();
			Object item = readItem(reader, context, collection);
			collection.add(item);
			reader.moveUp();
		}
	}

}
